package cn.stylefeng.guns.sys.modular.system.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.stylefeng.guns.base.pojo.page.LayuiPageFactory;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.sys.modular.system.entity.BtyMdFuzhumxz;
import cn.stylefeng.guns.sys.modular.system.mapper.BtyMdFuzhumxzMapper;
import cn.stylefeng.guns.sys.modular.system.model.params.BtyMdFuzhumxzParam;
import cn.stylefeng.guns.sys.modular.system.model.result.BtyMdFuzhumxzResult;
import cn.stylefeng.guns.sys.modular.system.service.BtyMdFuzhumxzService;
import cn.stylefeng.roses.core.reqres.response.ErrorResponseData;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 网上建店信息gcg_wsjd 服务实现类
 * </p>
 *
 * @author jiangge
 * @since 2021-09-08
 */
@Service
public class BtyMdFuzhumxzServiceImpl extends ServiceImpl<BtyMdFuzhumxzMapper, BtyMdFuzhumxz> implements BtyMdFuzhumxzService {

    @Override
    public void add(BtyMdFuzhumxzParam param) {
        BtyMdFuzhumxz entity = getEntity(param);
        this.save(entity);
    }

    @Override
    public void delete(BtyMdFuzhumxzParam param) {
        this.removeById(getKey(param));
    }

    @Override
    public void update(BtyMdFuzhumxzParam param) {
        BtyMdFuzhumxz oldEntity = getOldEntity(param);
        BtyMdFuzhumxz newEntity = getEntity(param);
        ToolUtil.copyProperties(newEntity, oldEntity);
        this.updateById(newEntity);
    }

    @Override
    public BtyMdFuzhumxzResult findBySpec(BtyMdFuzhumxzParam param) {
        return null;
    }

    @Override
    public List<BtyMdFuzhumxzResult> findListBySpec(BtyMdFuzhumxzParam param) {
        return null;
    }

    @Override
    public LayuiPageInfo findPageBySpec(BtyMdFuzhumxzParam param) {
        Page pageContext = getPageContext();
        IPage page = this.baseMapper.customPageList(pageContext, param);
        return LayuiPageFactory.createPageInfo(page);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseData importFzmxz(MultipartFile file) throws Exception {
        //文件名
        String fileName = file.getOriginalFilename();

        if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
            throw new Exception("上传文件格式不正确");
        }
        boolean isExcel2003 = true;
        if (fileName.matches("^.+\\.(?i)(xlsx)$")) {
            isExcel2003 = false;
        }

        InputStream is = file.getInputStream();
        Workbook wb = null;
        if (isExcel2003) {
            wb = new HSSFWorkbook(is);
        } else {
            wb = new XSSFWorkbook(is);
        }

        //excel中多个sheet表，获取所有sheet表的数量
        //int sheets = wb.getNumberOfSheets();
        //TODO-1 默认就一个sheet
        Sheet sheet = wb.getSheetAt(0);
        //TODO-2 第一行第一列是资产负债表
        Row row1 = sheet.getRow(0);
        Cell row1Cell1 = row1.getCell(0);
        String tableName = row1Cell1.getStringCellValue();

        if (StringUtils.isNotBlank(tableName) && !tableName.trim().equals("辅助明细账")) {
            return ErrorResponseData.error("导入失败，第5行内容与《辅助明细账》规定格式不符");
        }

        //TODO-3.1 从内容的第一行获取会计年
        Row row2 = sheet.getRow(3);
        Cell row2Cell2 = row2.getCell(0);
        String row2Cell2Val = row2Cell2.getStringCellValue();
        String year = row2Cell2Val.substring(0, 4);
        Integer yearNum = Integer.valueOf(year);
        //TODO-3.2 从内容的第一行获取会计月
        Row row11 = sheet.getRow(12);
        Cell row11Cell1 = row11.getCell(0);
        String riqiMonth = getStringValueOfInt(row11Cell1);
        Integer monthNum = Integer.valueOf(riqiMonth);

        //TODO-5 获取第四行以下的门店及字段和内容
        List<BtyMdFuzhumxzParam> fzmxzList = new ArrayList<>();
        for (int r = 10; r <= sheet.getLastRowNum(); r++) {
            Row row = sheet.getRow(r);
            if (row == null) {
                continue;
            }
            //月
            String month = rmoveZeroAndDot(getStringValue(row.getCell(0)));

            if (StringUtils.isNotBlank(month) && month.trim().equals("核算单位：")) {
                break;
            }

            //日
            String day = rmoveZeroAndDot(getStringValue(row.getCell(1)));

            if (StringUtils.isBlank(month) && StringUtils.isBlank(day)) {
                continue;
            }
            //科目名称
            String kmcode = rmoveZeroAndDot(getStringValue(row.getCell(2)));
            String km = rmoveZeroAndDot(getStringValue(row.getCell(3)));
            String yaoma = rmoveZeroAndDot(getStringValue(row.getCell(4)));
            String dm = rmoveZeroAndDot(getStringValue(row.getCell(5)));
            //部门档案名称 【部门档案：0411003\【部门档案：0411003\廊坊大城鑫达新天地店】】
//            String bmda = rmoveZeroAndDot(getStringValue(row.getCell(3)));
//
//            try {
//                String yaoma = bmda.substring(bmda.lastIndexOf("：") + 1, bmda.lastIndexOf("\\"));
//            } catch (Exception e) {
//                System.out.println(bmda);
//            }
//            String yaoma = bmda.substring(bmda.lastIndexOf("：") + 1, bmda.lastIndexOf("\\"));
//            String dm = bmda.substring(bmda.lastIndexOf("\\") + 1, bmda.lastIndexOf("】】"));


            //凭证号
            String pzh = rmoveZeroAndDot(getStringValue(row.getCell(6)));
            //摘要
            String zy = rmoveZeroAndDot(getStringValue(row.getCell(7)));
            //对方科目
            String dfkm = rmoveZeroAndDot(getStringValue(row.getCell(8)));
            //借方
            String jf = rmoveZeroAndDot(getStringValue(row.getCell(9)));
            //贷方
            String df = rmoveZeroAndDot(getStringValue(row.getCell(10)));
            //方向
            String fx = rmoveZeroAndDot(getStringValue(row.getCell(11)));
            //余额
            String ye = rmoveZeroAndDot(getStringValue(row.getCell(12)));

            BtyMdFuzhumxzParam fuzhumxzParam = new BtyMdFuzhumxzParam();
            fuzhumxzParam.setYaoma(yaoma);
            fuzhumxzParam.setDm(dm);
            //fuzhumxzParam.setRiqi(riqi);
            fuzhumxzParam.setKjYear(yearNum);
            fuzhumxzParam.setKjMonth(Integer.valueOf(month));
            fuzhumxzParam.setKjDay(Integer.valueOf(day));
            fuzhumxzParam.setKemu(km);
            fuzhumxzParam.setBumendangan("【部门档案："+yaoma+"\\【部门档案："+yaoma+"\\"+dm+"】】");
            fuzhumxzParam.setPingzhenghao(pzh);
            fuzhumxzParam.setDuifangKemu(dfkm);
            fuzhumxzParam.setJie(jf);
            fuzhumxzParam.setDai(df);
            fuzhumxzParam.setZaiyao(zy);
            fuzhumxzParam.setFangxiang(fx);
            fuzhumxzParam.setYue(getDecimalVal(ye));
            fzmxzList.add(fuzhumxzParam);
        }

        // TODO-5 保存之前删除之前存入的当月数据
        this.baseMapper.deleteFzmxzData(yearNum, monthNum);

        if (CollectionUtil.isNotEmpty(fzmxzList)) {
            for (BtyMdFuzhumxzParam data : fzmxzList) {
                this.add(data);
            }
        }

        return ResponseData.success();
    }

    private BigDecimal getDecimalVal(String val) {
        if (StringUtils.isBlank(val)) {
            return new BigDecimal("0");
        }
        return new BigDecimal(val);
    }

    @Override
    public List<BtyMdFuzhumxzResult> findAllFzmxzData(BtyMdFuzhumxzParam param) {
        List<BtyMdFuzhumxzResult> list = this.baseMapper.findAllFzmxzData(param);
        return list;
    }

    private Serializable getKey(BtyMdFuzhumxzParam param) {
        return param.getBtyMdFuzhumxzId();
    }

    private Page getPageContext() {
        return LayuiPageFactory.defaultPage();
    }

    private BtyMdFuzhumxz getOldEntity(BtyMdFuzhumxzParam param) {
        return this.getById(getKey(param));
    }

    private BtyMdFuzhumxz getEntity(BtyMdFuzhumxzParam param) {
        BtyMdFuzhumxz entity = new BtyMdFuzhumxz();
        ToolUtil.copyProperties(param, entity);
        return entity;
    }

    private String rmoveZeroAndDot(String s) {
        if (s.isEmpty()) {
            return "";
        }
        if (s.indexOf(".") > 0) {
            s = s.replaceAll("0+?$", "");
            s = s.replaceAll("[.]$", "");
        }
        return s;
    }



    private String getStringValue(Cell cell) {
        if (cell == null) {
            return "";
        }

        CellType cellType = cell.getCellType();
        if (cellType == CellType.NUMERIC) {
            Double numericCellValue = cell.getNumericCellValue();
            return numericCellValue.toString();
        } else if (cellType == CellType.BLANK) {
            //空值型
            return "";
        } else {
            String str = cell.getStringCellValue();
            try {
                return str;
            } catch (NumberFormatException ex) {
            }
            return "解析失败";
        }
    }

    private String getStringValueOfInt(Cell cell) {
        if (cell == null) {
            return "";
        }

        CellType cellType = cell.getCellType();
        if (cellType == CellType.NUMERIC) {
            Double numericCellValue = cell.getNumericCellValue();
            return numericCellValue.intValue()+"";
        } else if (cellType == CellType.BLANK) {
            //空值型
            return "";
        } else {
            String str = cell.getStringCellValue();
            try {
                return str;
            } catch (NumberFormatException ex) {
            }
            return "解析失败";
        }
    }

}
